#include "registerwindow.h"
#include "ui_registerwindow.h"
#include <QStyle>
#include <QScreen>
#include <QApplication>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include "../../thread/ReceiveThread.h"
#include <QButtonGroup>

extern ReceiveThread* recvThread;

RegisterWindow::RegisterWindow(DbHandler* dbHandler, QWidget *parent) :
    QWidget(parent), dbHandler(dbHandler),
    ui(new Ui::RegisterWindow),
    photoPath("")
{
    ui->setupUi(this);
    QButtonGroup *group = new QButtonGroup(this);   // 只要 parent 正确，会自动释放
    group->setExclusive(true);                      // 互斥
    group->addButton(ui->checkBox);
    group->addButton(ui->checkBox_2);


    // 设置窗口居中
    setGeometry(
        QStyle::alignedRect(
            Qt::LeftToRight,
            Qt::AlignCenter,
            size(),
            QApplication::primaryScreen()->availableGeometry()
        )
    );
    
    // 设置回车键确认
    connect(ui->lineEdit_realname, &QLineEdit::returnPressed, this, &RegisterWindow::on_pushButton_confirm_clicked);
    connect(ui->lineEdit_password, &QLineEdit::returnPressed, this, &RegisterWindow::on_pushButton_confirm_clicked);

    connect(recvThread, &ReceiveThread::recvDbStatus, this, &RegisterWindow::recvDbStatus);
    
    // 清除状态信息
    clearStatus();
}

RegisterWindow::~RegisterWindow()
{
    delete ui;
}

void RegisterWindow::recvDbStatus(const QByteArray &status, quint16 userId) {
    if (status == "SUCCESS_REG") {
        showStatus("注册成功！", false);
    } else if (status == "ERROR") {
        showStatus("数据库错误");
    }
}

void RegisterWindow::showEvent(QShowEvent *event)
{
    setGeometry(
        QStyle::alignedRect(
            Qt::LeftToRight,
            Qt::AlignCenter,
            size(),
            QApplication::primaryScreen()->availableGeometry()
        )
    );
    QWidget::showEvent(event);
}

void RegisterWindow::on_pushButton_upload_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
        tr("选择头像"), "",
        tr("图片文件 (*.png *.jpg *.jpeg *.bmp *.gif);;所有文件 (*)"));
    
    if (!fileName.isEmpty()) {
        photoPath = fileName;
        
        // 显示选择的图片
        QPixmap pixmap(fileName);
        if (!pixmap.isNull()) {
            // 缩放图片以适应显示区域
            QPixmap scaledPixmap = pixmap.scaled(ui->label_photo_display->size(), 
                                                Qt::KeepAspectRatio, 
                                                Qt::SmoothTransformation);
            ui->label_photo_display->setPixmap(scaledPixmap);
            ui->label_photo_display->setScaledContents(true);
        } else {
            showStatus("无法加载图片文件");
        }
    }
}

//这里可以告知服务器用户是专家还是工业人员，自动互斥
void RegisterWindow::on_pushButton_confirm_clicked()
{
    if (!validateInput()) {
        return;
    }
    quint16 userType = 0;

    if(ui->checkBox->isChecked()) userType = 0;     //如果是工业人员

    if(ui->checkBox_2->isChecked()) userType = 1;    //如果是专家

    QString username = ui->lineEdit_realname->text().trimmed();
    QString password = ui->lineEdit_password->text();
    
    showStatus("正在创建账户...", false);
    
    dbHandler->tryRegister(username, 0, password, userType);
}

void RegisterWindow::on_pushButton_back_clicked()
{
    emit backToLogin();
}

void RegisterWindow::showStatus(const QString &message, bool isError)
{
    ui->label_status->setText(message);
    if (isError) {
        ui->label_status->setStyleSheet("color: red; font-size: 12px;");
    } else {
        ui->label_status->setStyleSheet("color: blue; font-size: 12px;");
    }
}

void RegisterWindow::clearStatus()
{
    ui->label_status->setText("");
}

bool RegisterWindow::validateInput()
{
    QString realname = ui->lineEdit_realname->text().trimmed();
    QString password = ui->lineEdit_password->text();
    
    if (realname.isEmpty()) {
        showStatus("请输入用户名");
        ui->lineEdit_realname->setFocus();
        return false;
    }
    
    if (password.isEmpty()) {
        showStatus("请输入密码");
        ui->lineEdit_password->setFocus();
        return false;
    }
    
    if (realname.length() < 1) {
        showStatus("用户名至少需要1个字符");
        ui->lineEdit_realname->setFocus();
        return false;
    }
    
    if (password.length() < 1) {
        showStatus("密码至少需要1个字符");
        ui->lineEdit_password->setFocus();
        return false;
    }
    if (!hasCheckedGender()) {
        showStatus("请选择您的身份");
        return false;
    }

    return true;
}

void RegisterWindow::saveUserInfo(const QString &username, const QString &realname, const QString &photoPath)
{
    // 创建用户信息目录
    QDir dir;
    if (!dir.exists("userImformation")) {
        dir.mkdir("userImformation");
    }
    
    // 保存用户名到文件
    QFile userNameFile("userImformation/userName.txt");
    if (userNameFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&userNameFile);
        out.setCodec("UTF-8");
        out << realname;
        userNameFile.close();
    }
    
    // 保存其他信息到文件
    QFile otherFile("userImformation/other.txt");
    if (otherFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&otherFile);
        out.setCodec("UTF-8");
        out << "新用户";
        otherFile.close();
    }
    
    // 复制头像文件
    if (!photoPath.isEmpty()) {
        QFile::copy(photoPath, "userImformation/avatar.png");
    } else {
        // 如果没有选择头像，创建一个默认的
        QPixmap defaultAvatar(100, 100);
        defaultAvatar.fill(Qt::lightGray);
        defaultAvatar.save("userImformation/avatar.png", "PNG");
    }
}

//是否选择了身份
bool RegisterWindow::hasCheckedGender()
{
    return ui->checkBox->isChecked() || ui->checkBox_2->isChecked();
}
